#ifndef UTIL_H_INCLUDED
#define UTIL_H_INCLUDED

#include <stdarg.h>
#include <string.h>
/*
  Removes trailing newlines from strings
*/
void chomp(char* string)
{
    int len = strlen(string);
    int i;
    for (i = len-1; i >= 0; i -= 1)
    {
        if (string[i] == '\r' || string[i] == '\n')
        {
            string[i] = '\0';
        }
        else
        {
            return;
        }
    }
}

// Tells the compiler that this function never returns
void die(const char* msg, ...) __attribute__ ((noreturn));

void die(const char* msg, ...)
{
    va_list args;
    va_start(args, msg);
    vfprintf(stderr, msg, args);
    va_end(args);
    exit(1);
}

#ifdef DEBUG
#define CHECK_PTR(X)                            \
    do {                                        \
        if ((X) == NULL)                        \
        {                                       \
            perror("malloc");                   \
            exit(1);                            \
        }                                       \
    } while(0)
#else
#define CHECK_PTR(X) ;
#endif


#define CHECK_ARGS

#ifdef CHECK_ARGS
#define CHECK_ARG(X)                                                    \
    do {                                                                \
        if ((X) == NULL)                                                \
        {                                                               \
            die("Argument \"%s\" to function \"%s\" was NULL\n", #X, __FUNCTION__); \
        }                                                               \
    } while(0)
#else
#define CHECK_ARG(X) ;
#endif
#endif //UTIL_H_INCLUDED

